package com.kakarote.oa.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.kakarote.common.field.utils.FieldUtil;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.oa.entity.PO.OaLogTemplateFieldExtend;
import com.kakarote.oa.mapper.OaLogTemplateFieldExtendMapper;
import com.kakarote.oa.service.IOaLogTemplateFieldExtendService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author wanli
 * @description 针对表【wk_oa_log_template_field_extend(自定义字段表)】的数据库操作Service实现
 * @createDate 2022-07-05 16:25:26
 */
@Service
public class OaLogTemplateFieldExtendServiceImpl extends BaseServiceImpl<OaLogTemplateFieldExtendMapper, OaLogTemplateFieldExtend>
        implements IOaLogTemplateFieldExtendService {

    @Override
    public List<OaLogTemplateFieldExtend> queryCrmFieldExtend(Long parentFieldId) {
        List<OaLogTemplateFieldExtend> fieldExtends = lambdaQuery().eq(OaLogTemplateFieldExtend::getParentFieldId, parentFieldId).list();
        FieldUtil.recordToFormType(fieldExtends);
        return fieldExtends;
    }

    @Override
    public boolean saveOrUpdateCrmFieldExtend(List<OaLogTemplateFieldExtend> crmFieldExtendList, Long parentFieldId, boolean isUpdate) {
        if (parentFieldId == null) {
            return false;
        }
        if (isUpdate) {
            this.deleteCrmFieldExtend(parentFieldId);
        }
        for (OaLogTemplateFieldExtend fieldExtend : crmFieldExtendList) {
            if (ObjectUtil.isEmpty(fieldExtend.getDefaultValue())) {
                fieldExtend.setDefaultValue("");
            } else {
                boolean isNeedHandle = FieldUtil.equalsByType(fieldExtend.getType(), FieldEnum.AREA, FieldEnum.AREA_POSITION, FieldEnum.CURRENT_POSITION);
                if (isNeedHandle) {
                    fieldExtend.setDefaultValue(JSON.toJSONString(fieldExtend.getDefaultValue()));
                }
                if (fieldExtend.getDefaultValue() instanceof Collection) {
                    fieldExtend.setDefaultValue(StrUtil.join(Const.SEPARATOR, fieldExtend.getDefaultValue()));
                }
            }
            fieldExtend.setId(null);
            fieldExtend.setParentFieldId(parentFieldId);
            save(fieldExtend);
        }
        return true;
    }

    @Override
    public boolean deleteCrmFieldExtend(Long parentFieldId) {
        return lambdaUpdate().eq(OaLogTemplateFieldExtend::getParentFieldId, parentFieldId).remove();
    }
}




